<?php
if(!defined('IN_WOGU')) {
    exit('Access Denied');
}

class Router
{
    static protected $_config = null;
    
    public function __construct() {
        self::$_config = Loader::loadConfig('router');
    }
    
    public function route(Request $request) {
        $url = isset($_GET['url']) ? str_replace('index.php', '', $_GET['url']) : '';
        if(URL_REWRITE && $url != '') {
            $params = self::parse($_GET['url']);
        } else {
            $config = self::$_config[!empty($_GET['m']) && isset(self::$_config[$_GET['m']]) ? $_GET['m'] : 'default'];
            $params = array(
                'module'     => empty($_GET['m']) ?  $config['module'] : $_GET['m'],
                'controller' => empty($_GET['c']) ? $config['controller'] : $_GET['c'],
                'action'     => empty($_GET['a']) ? $config['action'] : $_GET['a'],
                'params'     => isset($config['params']) ? $config['params'] : array()
            );
        }
        
        if(!empty($_GET)) {
            foreach($_GET as $k => $v) {
                $params['params'][$k] = $v;
            }
        }

        $request->set_module($params['module']);
        $request->set_controller($params['controller']);
        $request->set_action($params['action']);
        $request->setParams($params['params']);
    }
    
    static public function parse($url) {
        $params = empty($url) ? array() : explode('-', str_replace('.htm', '', $url));
        $config = self::$_config[!empty($params[0]) && isset(self::$_config[$params[0]]) ? $params[0] : 'default'];
        $return['module'] = empty($params[0]) ? $config['module'] : $params[0];
        $return['controller'] = empty($params[1]) ? $config['controller'] : $params[1];
        $return['action'] = empty($params[2]) ? $config['action'] : $params[2];
        $return['params'] = isset($config['params']) ? $config['params'] : array();
        
        $len = count($params);
        if(3 < $len) {
            for($i = 3; $i < $len; $i++) {
                if(empty($params[$i])) {
                    ++$i;
                    continue;
                }
                
                $return['params'][$params[$i]] = isset($params[$i+1]) ? $params[++$i] : '';
            }
        }
        
        return $return;
    }
}